<template>
  <div id="bg">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="login-box" >
      <h3 class="login-title">欢迎登录</h3>
      <el-form-item label="账号" prop="userName">
        <el-input type="text" placeholder="请输入账号" v-model="form.userName"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
      </el-form-item>
      <el-form-item class="captcha" label="验证码" prop="code">
          <el-input class="code" type="text" placeholder="点击图片刷新验证码" v-model="form.code"/>
          <el-image :src="codeImg" class="codeImg" @click="changeVerifyCode()"></el-image>
      </el-form-item>

      <el-form-item>
        <el-button class="btn-login" type="primary" v-on:click="onSubmit('form')">登录</el-button>
        <el-button class="btn-login" type="primary" v-on:click="onRegister('forgetPwdForm')" round style="margin-right:40px">注册</el-button>
        <el-checkbox v-model="checked"@change="checkIt">管理员</el-checkbox>
        <el-link type="info" class="forget" @click="onForget">忘记密码？</el-link>
      </el-form-item>
    </el-form>

    <el-dialog
        title="温馨提示"
        :visible.sync="dialogVisible"
        width="30%"
        append-to-body
    >
      <span>请输入认证信息！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="温馨提示"
        :visible.sync="dialogLogin"
        width="30%"
        append-to-body
    >
      <span>输入信息有误请检查！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogLogin = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title=registerOrForget
               :visible.sync="dialogForget"
               width="30%"
               append-to-body
    >
      <el-form label-width="120px" ref="forgetPwdForm" :model="forgetPwdForm" :rules="rules">
        <el-row>
          <el-form-item prop="sex" label="性别：" v-if="register">
            <el-radio-group v-model="forgetPwdForm.sex">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
            <el-form-item prop="userName" label="账号：" v-if="register">
              <el-input v-model="forgetPwdForm.userName"></el-input>
            </el-form-item>
        </el-row>
        <el-row>
              <el-form-item prop="phone" label="手机号：">
                <el-input v-model="forgetPwdForm.phone" maxlength="11"></el-input>
            </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item prop="code" label="验证码：">
              <el-input v-model="forgetPwdForm.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-button @click="sendCodeMsg()" :disabled="disabled">{{sendCode}}</el-button>
          </el-col>
        </el-row>
        <el-form-item prop="newPassword" label="新密码">
          <el-input type="password" v-model="forgetPwdForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item prop="repeatPassword" label="确认密码">
          <el-input type="password" v-model="forgetPwdForm.repeatPassword"></el-input>
        </el-form-item>

      </el-form>
      <template slot="footer">
        <el-button type="default" @click="dialogForget = false">取消</el-button>
        <el-button type="primary" @click="forget('forgetPwdForm')">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {apiLogin,apiAdminLogin, apiForgetPassword, apiSendCodeMsg,apiRegister} from "@/assets/api/LoginAPI";
import "@/assets/js/encrypt"

export default {
  name: "LoginView",
  data() {
    return {
      form: {
        userName: 'admin',
        password: '123456',
        code:'',
        role:1
      },
      forgetPwdForm:{
        userName:'',
        newPassword:'',
        repeatPassword:'',
        code:'',
        phone:''
      },
      registerOrForget:'',
      rs:0,
      disabled:false,
      sendCode: "发送验证码",
      // 表单验证，需要在 el-form-item 元素中增加 prop 属性
      rules: {
        userName: [
          {required: true, message: '账号不可为空', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不可为空', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '验证码不可为空', trigger: 'blur'}
        ],
        newPassword: [
          {
            required: true, message: "新密码不能为空", trigger: "blur"
          },
        ],
        repeatPassword: [
          {
            required: true, message: "重置密码不能为空", trigger: "blur"
          }
        ],
        stuEmail: [{required: true, message: '邮箱不可为空', trigger: 'blur'},{pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱不正确'}],
        roleId: [{required: true, message: '角色不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        sex: [{required: true, message: '性别不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        phone: [{required: true, message: '手机号不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'},{required: true , pattern :/^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/,message: "电话号码格式不正确"}],

      },
      codeImg:"",
      // 对话框显示和隐藏
      dialogVisible: false,
      dialogLogin:false,
      dialogForget:false,
      register:false,
      checked: false
    }
  },
  methods: {
    async onSubmit(formName) {
      // 为表单绑定验证功能
      this.$refs[formName].validate(async (valid) => {
        if (valid) {

          const login = {
            userName: this.Rsa.rsaPublicData(this.form.userName),
            password: this.Rsa.rsaPublicData(this.form.password),
            code: this.Rsa.rsaPublicData(this.form.code),
            role: this.Rsa.rsaPublicData(this.form.role),
          }
            await apiLogin(this.Rsa.rsaPublicData(JSON.stringify(this.form))).then(resp => {
              if (String(resp.data.code) === '1') {
                this.$store.commit('login',resp.data.data.realName,resp.data.data);
                // 使用 vue-router 路由到指定页面，该方式称之为编程式导航
                if (this.form.role === 0){
                  this.$router.push("/Home");
                }else {
                  this.$router.push("/User");
                }
              }else {
                this.dialogLogin = true;
                return
              }
            })
        }
       else {
          this.dialogVisible = true;
          return false;
        }
      });
    },
    changeVerifyCode() {
      this.axios.get("api/getKaptchaImage", {
        responseType: "arraybuffer"
      })
          .then(response => {
            return 'data:image/png;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
          }).then(res => {
        this.codeImg = res;
      })
    },
    regexPhone() {
      const reg = /^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/;
      if (this.forgetPwdForm.phone == '') {
        this.$message("请输入手机号码")
        return false;
      } else if (!reg.test(this.forgetPwdForm.phone)) {
        this.$message("手机号格式不正确")
        return false;
      } else {
        return true;
      }
    },
    //发送验证码
    sendCodeMsg() {
      let _this = this;
      if (_this.regexPhone()) {
        let num = 60;
        const timer = setInterval(function () {
          num--;
          _this.disabled = true;
          _this.sendCode = num + '秒后重新获取';
          if (num === 0) {
            _this.sendCode = '获取验证码';
            _this.disabled = false;
            clearInterval(timer)
          }
        }, 1000);
        const params = {
          phone: this.forgetPwdForm.phone
        }
        apiSendCodeMsg(params)
      }

    },
    checkIt(){
      this.checked ? this.form.role = 0 : this.form.role = 1
    },
    //点击忘记密码
    onForget(){
      this.registerOrForget = "忘记密码"
      if(this.register){
        this.forgetPwdForm={brand_right:0}
      }
      this.dialogForget = true
      this.register = false
    },
    //点击注册
    onRegister(){
      this.registerOrForget = "注册"
      if(!this.register){
        this.forgetPwdForm={brand_right:0}
      }
      this.register = true
      this.dialogForget = true
    },
    //修改密码和注册
    forget(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if(this.register){
            apiRegister(this.forgetPwdForm).then(resp => {
              if (String(resp.data.code) === '1') {
                this.$message("注册成功")
                this.forgetPwdForm={brand_right:0}
                this.dialogForget = false
              } else {
                this.$message(resp.data.msg)
              }
            })
          }else{
            apiForgetPassword(this.forgetPwdForm).then(resp => {
              if (String(resp.data.code) === '1') {
                this.$message("修改成功")
                this.forgetPwdForm={brand_right:0}
                this.dialogForget = false
              } else {
                this.$message("修改失败")
              }
            })
          }

        } else {
          this.dialogVisible = true;
          return false;
        }
      });
    },
  },
  created() {
    this.changeVerifyCode()
  },

}
</script>

<style scoped>
.login-box {
  border: 1px solid #DCDFE6;
  width: 350px;
  margin: 180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
  background-color:whitesmoke;
}

.login-title {
  text-align: center;
  margin: 0 auto 40px auto;
  color: #303133;
}
.code {
  float: left;
  width: 70%;
}
.btn-login {
  float: left;
}
.forget {
  float: right;
}
.codeImg {
  float: right;
  width: 70px;
}
#bg{
  background:url('../assets/texture/bg.webp');
  width:100%;
  height:100%;
  position:fixed;
  background-size:100% 100%;
}
</style>

